using System.Text.RegularExpressions;

namespace org.jawk.jrt
{
	/// <summary>
	/// A pair of regular expressions such that matching means
	/// previous text has matched the first regex, but not the
	/// second regex.
	/// </summary>
	/// <remarks>
	/// A pair of regular expressions such that matching means
	/// previous text has matched the first regex, but not the
	/// second regex.
	/// When text matches the second regex, it is still considered
	/// a match.  However, subsequent matching attempts are false
	/// unless the first regex is matched again.
	/// <p>
	/// If text matches both the first and second regex, the entry
	/// is considered a match, but subsequent entries are not considered
	/// matched (unless the text matches the first regex).
	/// </remarks>
	public class PatternPair
	{
		private Regex p1;

        private Regex p2;

		private bool within = false;

		public PatternPair(string s1, string s2)
		{
			p1 = new Regex(s1);
			p2 = new Regex(s2);
		}

		/// <summary>
		/// Text is matched against this regex pair, returning true only
		/// if this or previous text matches the first regex, up until
		/// the text is matched against the second regex.
		/// </summary>
		/// <remarks>
		/// Text is matched against this regex pair, returning true only
		/// if this or previous text matches the first regex, up until
		/// the text is matched against the second regex.
		/// <p>
		/// </remarks>
		/// <param name="str">
		/// Text to match against the first and second
		/// regular expressions.
		/// </param>
		/// <returns>
		/// true if this or previous text matches the first regex,
		/// up until text matches the second regex, which is still considered
		/// a match, but subsequent text is not considered a match
		/// (unless, of course, the text matches the first regex).
		/// </returns>
		public virtual bool Matches(string str)
		{
			if (p1.IsMatch(str))
			{
				within = true;
			}
			if (within && p2.IsMatch(str))
			{
				within = false;
				return true;
			}
			// inclusive
			return within;
		}

		public override string ToString()
		{
			return p1 + "," + p2;
		}
	}
}
